/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SFI.Controlador;

import SFI.Reporte.FacturaImp;
import SFI.util.Fecha;
import factura.modelo.Articulo;
import factura.modelo.DetalleFactura;
import factura.modelo.Factura;
import java.util.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zkex.zul.Jasperreport;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

/**
 *
 * @author Romig Sevilla
 * @version 1.0
 */
public class ControladorFactura extends ControladorCliente {

    Double subtotal = 0D;
    Double iva = 0D;
    Double total = 0D;
    int cantidad = 1;
    DetalleFactura detallFactura;
    Factura factura;
    List<DetalleFactura> detalleFactura;

    public Double getIva() {
        return iva;
    }

    public void setIva(Double iva) {
        this.iva = iva;
    }

    public Double getSubtotal() {
        return subtotal;
    }

    public void setSubtotal(Double subtotal) {
        this.subtotal = subtotal;
    }

    public Double getTotal() {
        return total;
    }

    public void setTotal(Double total) {
        this.total = total;
    }

    public int getCantidad() {
        return cantidad;
    }

    public void setCantidad(int cantidad) {
        this.cantidad = cantidad;
    }

    @NotifyChange({"mostrarArticulo", "articulosVenta", "articulos", "subtotal", "iva", "total"})
    @Command
    public void AgregarArticulo() {

        if (selectedArticulo.getStock() > 0 && selectedArticulo.getStock() >= cantidad) {
            selectedArticulo.setCantidad(cantidad);
            subtotal = subtotal + selectedArticulo.getSubtotalArt();
            iva = subtotal * (ivaActual / 100);
            total = subtotal + iva;
            ArticuloStatus arVen = new ArticuloStatus(selectedArticulo, false);
            articulosVenta.add(arVen);

            disminuirStock();

        } else {
            Messagebox.show("No existe cantidad de  " + selectedArticulo.getDescripcion());

        }

    }

    public void disminuirStock() {
        Articulo art = articulos.get(articulos.indexOf(selectedArticulo));
        art.setStock(art.getStock() - selectedArticulo.getCantidad());
        articulos.set(articulos.indexOf(selectedArticulo), art);
    }

    @NotifyChange({"articulosVenta", "articulos", "selected", "subtotal", "iva", "total"})
    @Command
    public void imprimirFactura() {
        //System.out.println("articulos size " + articulosVenta.size());

        if (articulosVenta.size() > 0) {
            FacturaImp.allDetalleFactura.clear();
            factura = new Factura();
            factura.setIdCliente(selected);
            factura.setFecha(new Date());
            factura.setIva(iva);
            factura.setDescuento(0);
            factura.setTotalop(total);
            detalleFactura = new LinkedList<DetalleFactura>();


            for (ArticuloStatus articulost : articulosVenta) {
                FacturaImp factRepor = new FacturaImp();
                detallFactura = new DetalleFactura();
                detallFactura.setCantidad(articulost.getAr().getCantidad());
                detallFactura.setIdArticulo(articulost.getAr());
                detallFactura.setIdFactura(factura);
                detalleFactura.add(detallFactura);
                factRepor.setCatidad(Double.parseDouble(String.valueOf(articulost.getAr().getCantidad())));
                factRepor.setDescripcion(articulost.getAr().getDescripcion());
                factRepor.setPrecio(Double.valueOf(String.valueOf(articulost.getAr().getPrecio())));
                factRepor.setSubtA(articulost.getAr().getSubtotalArt());
                FacturaImp.allDetalleFactura.add(factRepor);


            }
            factura.setDetalleFacturaList(detalleFactura);
            int result =
                    deleg.insert(factura);

            if (result == 0) {

                for (ArticuloStatus articulost : articulosVenta) {
                    Articulo art =
                            deleg.buscar(Articulo.class, articulost.getAr().getId());
                    art.setStock(art.getStock() - articulost.getAr().getCantidad());
                    System.out.println("valor segundo " + articulost.getAr().getId());
                    deleg.modificar(art);

                }

            }
            Long idfactura=deleg.obtenerSecuenId();

            procesarFactura(idfactura);

            articulosVenta.clear();
            selected = null;
            subtotal = 0D;
            iva = 0D;
            total = 0D;

        } else {

            Messagebox.show("!!!Ingrese Articulos!!!!");
        }

    }
    //region editable
    private boolean displayEdit = true;

    public boolean isDisplayEdit() {
        return displayEdit;
    }

    @NotifyChange({"articulosVenta", "displayEdit"})
    public void setDisplayEdit(boolean displayEdit) {
        this.displayEdit = displayEdit;
    }

    @Command
    public void changeEditableStatus(@BindingParam("articulostatus") ArticuloStatus lcs) {
        lcs.setEditingStatus(!lcs.getEditingStatus());
        refreshRowTemplate(lcs);
    }

    @NotifyChange({"articulosVenta", "displayEdit", "subtotal", "iva", "total"})
    @Command
    public void confirm(@BindingParam("articulostatus") ArticuloStatus ars) {
        subtotal = 0D;
        iva = 0D;
        total = 0D;
        for (ArticuloStatus articulo : articulosVenta) {
            subtotal = subtotal + articulo.getAr().getSubtotalArt();
            iva = subtotal * (ivaActual / 100);
            total = subtotal + iva;
        }

        changeEditableStatus(ars);
        refreshRowTemplate(ars);
    }

    @NotifyChange({"articulosVenta", "displayEdit", "subtotal", "iva", "total"})
    @Command
    public void EliminarArt(@BindingParam("articulostatus") ArticuloStatus as) {
        subtotal = subtotal - as.getAr().getSubtotalArt();
        iva = subtotal * (ivaActual / 100);
        total = subtotal + iva;
        articulosVenta.remove(articulosVenta.indexOf(as));
        as.setEditingStatus(!as.getEditingStatus());
        refreshRowTemplate(as);

    }

    public void refreshRowTemplate(ArticuloStatus lcs) {
        /*
         * This code is special and notifies ZK that the bean's value has
         * changed as it is used in the template mechanism. This stops the
         * entire Grid's data from being refreshed
         */
        BindUtils.postNotifyChange(null, null, lcs, "editingStatus");
    }

    public void procesarFactura(Long idfactura) {
        Fecha fecha=new Fecha();
        String type = "pdf";
        String path = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/factura");
        Window win = (Window) Executions.createComponents("/factura/report.zul", null,
                null);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("cliente", factura.getIdCliente().getNombclient());
        params.put("rif", factura.getIdCliente().getRif());
        params.put("direccion", factura.getIdCliente().getDireccion());
        params.put("Nfactura", idfactura);
        params.put("fecha", fecha.fechaActual(factura.getFecha()));
        params.put("subTotal", subtotal);
        params.put("iva", factura.getIva());
        params.put("total", factura.getTotalop());

        Jasperreport report = (Jasperreport) win.getFellow("report");
        report.setType(type);
        report.setSrc(path + "/factura.jasper");
        report.setParameters(params);
        report.setDatasource(new JRBeanCollectionDataSource(FacturaImp.generateColeccion()));


    }
}
